<template>
  <view class="page">
    <!-- 顶部车辆卡片 -->
    <view class="car-card">
      <image class="car-img" :src="carInfo.image" mode="aspectFill"></image>
      <view class="car-text">
        <view>{{carInfo.name}}</view>
        <view class="sub">{{carInfo.desc}}</view>
      </view>
    </view>

    <!-- 销售信息 -->
    <view class="section">
      <view class="section-title">销售信息</view>
      <view class="form-card">

        <!-- 指导价（元） -->
        <view class="cell">
          <view class="label">指导价（元）</view>
          <input class="ipt" type="digit" v-model="form.guidePrice" @input="onPriceInput($event, 'guidePrice')" placeholder="请输入" />
          <text class="ic">✎</text>
        </view>

        <!-- 出售价（元） -->
        <view class="cell">
          <view class="label">出售价（元）</view>
          <input class="ipt" type="digit" v-model="form.sellPrice" @input="onPriceInput($event, 'sellPrice')" placeholder="请输入" />
          <text class="ic">✎</text>
        </view>

        <!-- 销售顾问 -->
        <view class="cell">
          <view class="label">销售顾问</view>
          <input class="ipt" type="text" v-model="form.salesman" placeholder="请输入" />
          <text class="ic">✎</text>
        </view>

        <!-- 过户时间 -->
        <picker mode="date" :value="form.transferDate" @change="onTransferDateChange">
          <view class="cell">
            <view class="label">过户时间</view>
            <view class="value">{{ form.transferDate || '请选择日期' }}</view>
            <text class="ic">📅</text>
          </view>
        </picker>

      </view>
    </view>

    <!-- 买方付款信息（新区域） -->
    <view class="section">
      <view class="section-title">买方付款信息</view>
      <view class="form-card">
        
        <!-- 付款方式 -->
        <picker :range="paymentMethods" :value="paymentIndex" @change="onPaymentChange">
          <view class="cell">
            <view class="label">付款方式</view>
            <view class="value">{{ paymentMethods[paymentIndex] || '请选择' }}</view>
            <text class="ic">▾</text>
          </view>
        </picker>

        <!-- 首付金额 -->
        <view class="cell">
          <view class="label">首付金额</view>
          <input class="ipt" type="digit" v-model="form.downPayment" @input="onPriceInput($event, 'downPayment')" placeholder="请输入" />
          <text class="ic">✎</text>
        </view>

        <!-- 尾款金额（贷款） -->
        <view class="cell">
          <view class="label">尾款金额（贷款）</view>
          <input class="ipt" type="digit" v-model="form.loanAmount" @input="onPriceInput($event, 'loanAmount')" placeholder="请输入" />
          <text class="ic">✎</text>
        </view>
      </view>
    </view>

    <!-- 买方信息 -->
    <view class="section">
      <view class="section-title">买方信息</view>
      <view class="form-card">

        <!-- 姓名/公司名 -->
        <view class="cell">
          <view class="label">姓名/公司名</view>
          <input class="ipt" type="text" v-model="form.buyerName" placeholder="请输入" />
          <text class="ic">✎</text>
        </view>

        <!-- 身份证号/统一信用代码 -->
        <view class="cell">
          <view class="label">身份证号/统一信用代码</view>
          <input class="ipt" type="text" v-model="form.buyerIdNo" placeholder="请输入" />
          <text class="ic">✎</text>
        </view>

        <!-- 身份证正面 -->
        <view class="cell" @tap="chooseImage('idCardFront')">
          <view class="label">身份证正面</view>
          <view class="value">{{ pics.idCardFront ? '已选择' : '未上传' }}</view>
          <image
            v-if="pics.idCardFront && (pics.idCardFront.url || pics.idCardFront.path)"
            class="thumb"
            :src="pics.idCardFront.url || pics.idCardFront.path"
            mode="aspectFill"
            @tap.stop="previewImage('idCardFront')"
          />
          <text class="iconfont icon-tupian ic"></text>
        </view>

        <!-- 身份证反面 -->
        <view class="cell" @tap="chooseImage('idCardBack')">
          <view class="label">身份证反面</view>
          <view class="value">{{ pics.idCardBack ? '已选择' : '未上传' }}</view>
          <image
            v-if="pics.idCardBack && (pics.idCardBack.url || pics.idCardBack.path)"
            class="thumb"
            :src="pics.idCardBack.url || pics.idCardBack.path"
            mode="aspectFill"
            @tap.stop="previewImage('idCardBack')"
          />
          <text class="iconfont icon-tupian ic"></text>
        </view>

        <!-- 营业执照 -->
        <view class="cell" @tap="chooseImage('businessLicense')">
          <view class="label">营业执照</view>
          <view class="value">{{ pics.businessLicense ? '已选择' : '未上传' }}</view>
          <image
            v-if="pics.businessLicense && (pics.businessLicense.url || pics.businessLicense.path)"
            class="thumb"
            :src="pics.businessLicense.url || pics.businessLicense.path"
            mode="aspectFill"
            @tap.stop="previewImage('businessLicense')"
          />
          <text class="iconfont icon-tupian ic"></text>
        </view>

        <!-- 缴税行信息截图 -->
        <view class="cell" @tap="chooseImage('taxInfo')">
          <view class="label">缴税行信息截图</view>
          <view class="value">{{ pics.taxInfo ? '已选择' : '未上传' }}</view>
          <image
            v-if="pics.taxInfo && (pics.taxInfo.url || pics.taxInfo.path)"
            class="thumb"
            :src="pics.taxInfo.url || pics.taxInfo.path"
            mode="aspectFill"
            @tap.stop="previewImage('taxInfo')"
          />
          <text class="iconfont icon-tupian ic"></text>
        </view>
      </view>
    </view>

    <!-- 底部提交按钮 -->
    <view class="bottom-btn-box">
      <button class="submit-btn" @click="submit">提交</button>
    </view>
  </view>
</template>

<script>
import common_config from '@/static/js/common.js'
var config = common_config.config
var that
var userInfo

export default {
  data() {
    return {
      if_login: false, // 是否登录
      
      // 车辆信息（从上一页传递）
      carInfo: {
        id: '',
        name: '',
        desc: '',
        image: '',
        price: ''
      },

      // 表单数据
      form: {
        guidePrice: '', // 指导价
        sellPrice: '', // 出售价
        salesman: '', // 销售顾问
        transferDate: '', // 过户时间
        paymentMethod: '', // 付款方式
        downPayment: '', // 首付金额
        loanAmount: '', // 贷款金额
        buyerName: '', // 姓名/公司名
        buyerIdNo: '' // 身份证号/统一信用代码
      },

      // 付款方式选项
      paymentMethods: ['全款', '贷款', '分期'],
      paymentIndex: -1,

      // 图片（改为对象格式，包含 path 和 url）
      pics: {
        idCardFront: null, // 身份证正面 {path: '', url: ''}
        idCardBack: null, // 身份证反面
        businessLicense: null, // 营业执照
        taxInfo: null // 缴税行信息截图
      }
    }
  },

  onLoad(options) {
    that = this
    
    // 获取传递过来的车辆信息
    that.carInfo.id = options.car_id || ''
    that.carInfo.name = decodeURIComponent(options.car_name || '')
    that.carInfo.price = options.price ? decodeURIComponent(options.price) : ''
    that.carInfo.image = decodeURIComponent(options.image || 'https://kehu-1256834579.cos.ap-shanghai.myqcloud.com/yuanxiang/logo2.png')
    that.carInfo.desc = that.carInfo.price ? `展厅指导价 ${that.carInfo.price}` : '待定'

    // 初始化
    that.plusReady()
  },

  methods: {
    // 初始化
    plusReady() {
      var func1 = function() {
        that.no_login()
      }
      var func2 = function() {
        that.is_login()
      }
      common_config.common_if_login(func1, func2)
    },
    
    // 未登录
    no_login() {
      that.if_login = false
    },
    
    // 已登录
    is_login() {
      that.if_login = true
      userInfo = uni.getStorageSync('userInfo')
      userInfo = JSON.parse(userInfo)
    },
    
    // 金额输入限制（只能输入数字和一位小数点，第一位不能是小数点）
    onPriceInput(e, key) {
      let value = e.detail.value
      
      // 第一位不能是小数点
      if (value.startsWith('.')) {
        value = ''
      }
      
      // 只能包含数字和一个小数点
      value = value.replace(/[^\d.]/g, '') // 只保留数字和点
      
      // 只能有一个小数点
      const dotIndex = value.indexOf('.')
      if (dotIndex !== -1) {
        // 如果有小数点，保留第一个，删除后面的
        value = value.slice(0, dotIndex + 1) + value.slice(dotIndex + 1).replace(/\./g, '')
        
        // 小数点后只能一位
        const parts = value.split('.')
        if (parts[1] && parts[1].length > 1) {
          value = parts[0] + '.' + parts[1].slice(0, 1)
        }
      }
      
      that.form[key] = value
    },
    
    // 过户时间选择
    onTransferDateChange(e) {
      that.form.transferDate = e.detail.value
    },

    // 付款方式选择
    onPaymentChange(e) {
      that.paymentIndex = Number(e.detail.value)
      that.form.paymentMethod = that.paymentMethods[that.paymentIndex]
    },

    // 选择图片（参考 pinggu1）
    async chooseImage(key) {
      try {
        const r = await new Promise((resolve, reject) => {
          uni.chooseImage({
            count: 1,
            sizeType: ['compressed'],
            sourceType: ['album', 'camera'],
            success: resolve,
            fail: reject
          })
        })
        const p = r.tempFilePaths && r.tempFilePaths[0]
        if (!p) return
        that.$set(that.pics, key, { path: p, url: '' })
      } catch(e) {
        console.error('选择图片失败:', e)
      }
    },

    // 预览图片
    previewImage(key) {
      const pic = that.pics[key]
      if (pic) {
        const url = pic.url || pic.path
        if (url) {
          uni.previewImage({
            urls: [url],
            current: 0
          })
        }
      }
    },
    
    // URL 规范化（参考 pinggu1）
    normalizeUrl(u) {
      if (!u) return ''
      u = String(u).trim()
      if (/^https?:\/\//i.test(u)) return u
      if (/^\/\//.test(u)) return 'https:' + u
      const base = (config.cdn || config.request_url || '').replace(/\/+$/, '')
      if (!base) return u
      if (u[0] !== '/') u = '/' + u
      return base + u
    },
    
    // 解析上传返回（参考 pinggu1）
    parseUploadUrl(resp) {
      let raw = resp && resp.data, obj
      try {
        obj = typeof raw === 'string' ? JSON.parse(raw) : raw
      } catch(e) {
        obj = { code: 200, data: raw }
      }
      if (obj && Number(obj.code) === 200) {
        let url = ''
        if (typeof obj.data === 'string') url = obj.data
        else if (obj.data && typeof obj.data === 'object') url = obj.data.src || obj.data.url || ''
        else url = obj.url || obj.src || ''
        return that.normalizeUrl(url)
      }
      return ''
    },
    
    // 上传所有图片（参考 pinggu1）
    async uploadAllPics() {
      const uploadUrl = config.upload_url ? config.upload_url : (config.request_url + '/index/file/upload_img')
      const map = {}
      
      for (const k of Object.keys(that.pics)) {
        const pic = that.pics[k]
        
        // 如果没有图片，跳过（非必填）
        if (!pic || (!pic.path && !pic.url)) {
          map[k] = ''
          continue
        }
        
        // 如果已有服务端地址
        if (pic.url) {
          const norm = that.normalizeUrl(pic.url)
          that.$set(that.pics, k, { ...pic, url: norm })
          map[k] = norm
          continue
        }
        
        // 上传图片
        const url = await new Promise(resolve => {
          uni.uploadFile({
            url: uploadUrl + '?token=' + (userInfo?.token || ''),
            name: 'file',
            filePath: pic.path,
            formData: { scene: k },
            success: (res) => {
              const finalUrl = that.parseUploadUrl(res)
              resolve(finalUrl || '')
            },
            fail: () => resolve('')
          })
        })
        
        if (!url) {
          uni.showToast({
            title: '图片上传失败',
            icon: 'none'
          })
          return null
        }
        
        that.$set(that.pics, k, { path: pic.path, url })
        map[k] = url
      }
      
      return map
    },

    // 表单验证（从上到下检查所有必填项）
    validateForm() {
      // 1. 指导价（元）
      if (!that.form.guidePrice || that.form.guidePrice === '') {
        uni.showToast({ title: '请输入指导价', icon: 'none' })
        return false
      }
      
      // 2. 出售价（元）
      if (!that.form.sellPrice || that.form.sellPrice === '') {
        uni.showToast({ title: '请输入出售价', icon: 'none' })
        return false
      }
      
      // 3. 销售顾问
      if (!that.form.salesman || that.form.salesman.trim() === '') {
        uni.showToast({ title: '请输入销售顾问', icon: 'none' })
        return false
      }
      
      // 4. 过户时间
      if (!that.form.transferDate || that.form.transferDate === '') {
        uni.showToast({ title: '请选择过户时间', icon: 'none' })
        return false
      }
      
      // 5. 付款方式
      if (!that.form.paymentMethod || that.form.paymentMethod === '') {
        uni.showToast({ title: '请选择付款方式', icon: 'none' })
        return false
      }
      
      // 6. 首付金额
      if (!that.form.downPayment || that.form.downPayment === '') {
        uni.showToast({ title: '请输入首付金额', icon: 'none' })
        return false
      }
      
      // 7. 尾款金额（贷款）
      if (!that.form.loanAmount || that.form.loanAmount === '') {
        uni.showToast({ title: '请输入尾款金额', icon: 'none' })
        return false
      }
      
      // 8. 姓名/公司名
      if (!that.form.buyerName || that.form.buyerName.trim() === '') {
        uni.showToast({ title: '请输入姓名/公司名', icon: 'none' })
        return false
      }
      
      // 9. 身份证号/统一信用代码
      if (!that.form.buyerIdNo || that.form.buyerIdNo.trim() === '') {
        uni.showToast({ title: '请输入身份证号/统一信用代码', icon: 'none' })
        return false
      }
      
      // 10. 身份证正面
      if (!that.pics.idCardFront || (!that.pics.idCardFront.path && !that.pics.idCardFront.url)) {
        uni.showToast({ title: '请上传身份证正面', icon: 'none' })
        return false
      }
      
      // 11. 身份证反面
      if (!that.pics.idCardBack || (!that.pics.idCardBack.path && !that.pics.idCardBack.url)) {
        uni.showToast({ title: '请上传身份证反面', icon: 'none' })
        return false
      }
      
      // 12. 营业执照
      if (!that.pics.businessLicense || (!that.pics.businessLicense.path && !that.pics.businessLicense.url)) {
        uni.showToast({ title: '请上传营业执照', icon: 'none' })
        return false
      }
      
      // 13. 缴税行信息截图
      if (!that.pics.taxInfo || (!that.pics.taxInfo.path && !that.pics.taxInfo.url)) {
        uni.showToast({ title: '请上传缴税行信息截图', icon: 'none' })
        return false
      }
      
      return true
    },
    
    // 提交表单
    async submit() {
      // 先验证表单
      if (!that.validateForm()) {
        return
      }
      
      uni.showLoading({ title: '提交中' })
      
      // 上传所有图片
      const picUrls = await that.uploadAllPics()
      if (picUrls === null) {
        uni.hideLoading()
        return
      }
      
      // 付款方式映射：全款=1，贷款=2，分期=3
      let paymentMethodValue = 1 // 默认全款
      if (that.form.paymentMethod === '贷款') {
        paymentMethodValue = 2
      } else if (that.form.paymentMethod === '分期') {
        paymentMethodValue = 3
      }
      
      /**
       * 接口说明：
       * 接口地址：config.request_url + '/index/xiaoshou/submit?token=' + userInfo.token
       * 请求方式：POST
       * 请求参数：参考接口文档
       */
      
      uni.request({
        url: config.request_url + '/index/xiaoshou/submit?token=' + (userInfo?.token || ''),
        method: 'POST',
        header: { 'Content-Type': 'application/x-www-form-urlencoded' },
        data: {
          car_id: that.carInfo.id,
          car_name: that.carInfo.name,
          guide_price: that.form.guidePrice || '0.00',
          sell_price: that.form.sellPrice || '0.00',
          salesman: that.form.salesman || '',
          transfer_date: that.form.transferDate || '',
          payment_method: paymentMethodValue,
          down_payment: that.form.downPayment || '0.00',
          loan_amount: that.form.loanAmount || '0.00',
          buyer_name: that.form.buyerName || '',
          buyer_id_no: that.form.buyerIdNo || '',
          id_card_front: picUrls.idCardFront || '',
          id_card_back: picUrls.idCardBack || '',
          business_license: picUrls.businessLicense || '',
          tax_info: picUrls.taxInfo || ''
        },
        success: (res) => {
          uni.hideLoading()
          const r = res.data || {}
          if (r.code == 200) {
            uni.showToast({ title: '提交成功', icon: 'success' })
            setTimeout(() => {
              // 使用 redirectTo 关闭当前页面并跳转
              uni.redirectTo({ url: '/pages/index/sub_success?type=1' })
            }, 300)
          } else {
            uni.showToast({
              title: r.msg || '提交失败',
              icon: 'none'
            })
          }
        },
        fail: () => {
          uni.hideLoading()
          uni.showToast({
            title: '网络异常',
            icon: 'none'
          })
        }
      })
    }
  }
}
</script>

<style>
/* 页面与卡片 - 参考 pinggu1 */
.page {
  background: #f6f8ff;
  min-height: 100vh;
  padding: 32rpx 32rpx 140rpx;
}

.section {
  background: #fff;
  border-radius: 20rpx;
  padding: 24rpx;
  margin-bottom: 28rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.04);
}

.section-title {
  font-size: 30rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 12rpx;
}

.car-card {
  background: #fff;
  border-radius: 20rpx;
  padding: 20rpx;
  display: flex;
  gap: 20rpx;
  align-items: center;
  margin-bottom: 28rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
}

.car-img {
  width: 220rpx;
  height: 130rpx;
  border-radius: 12rpx;
  flex-shrink: 0;
}

.car-text {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  line-height: 1.6;
}

.car-text .sub {
  color: #777;
  font-size: 26rpx;
}

/* 表单表格 */
.form-card {
  background: #fff;
  border: 1rpx solid #e8eef6;
  border-radius: 16rpx;
  overflow: hidden;
}

.cell {
  display: flex;
  align-items: center;
  padding: 22rpx 18rpx;
  border-bottom: 1rpx solid #edf2f7;
  transition: background .15s, border-color .15s;
}

.cell:last-child {
  border-bottom: none;
}

.label {
  width: 240rpx;
  font-size: 28rpx;
  color: #475569;
  display: flex;
  align-items: center;
  gap: 6rpx;
}

.value {
  flex: 1;
  font-size: 28rpx;
  color: #64748b;
}

.ipt {
  flex: 1;
  border: none;
  outline: none;
  background: transparent;
  font-size: 28rpx;
  color: #111827;
}

.ic {
  width: 44rpx;
  text-align: right;
  font-size: 30rpx;
  color: #9aa5b1;
  margin-left: 10rpx;
}

.thumb {
  width: 72rpx;
  height: 72rpx;
  border-radius: 8rpx;
  margin-right: 12rpx;
}

input::placeholder {
  color: #a3aab3;
}

/* 提交按钮 */
.bottom-btn-box {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  padding: 18rpx 28rpx;
  box-shadow: 0 -4rpx 10rpx rgba(0,0,0,0.06);
}

.submit-btn {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  background: #007aff;
  color: #fff;
  font-size: 30rpx;
  border-radius: 45rpx;
  font-weight: 600;
  border: none;
}

.submit-btn:active {
  opacity: .92;
}
</style>

